﻿#define _CRT_SECURE_NO_WARNINGS  1
//一定要动手，例子不管多么简单，建议至少自己手敲一遍看看是否理解了里头的细枝末节。
//一定要学会思考，思考为什么要这样，而不是那样。还要举一反三地思考
#pragma once
#include<string>
#include<iostream>
using namespace std;
template <class T>
class MyArray {
private:
	
	T * _myarray;//指向在堆区开辟的真实数组
	int _capacity;//容量
	int _size;//大小
public:
	//有参构造
	MyArray(int capacity)
	{
		/*cout << "有参构造函数调用" << endl;*/
		this->_capacity = capacity;
		this->_size = 0;
		this->_myarray = new T[this->_capacity];
	}
	
	//拷贝构造函数
	MyArray(const MyArray& arr)
	{
		//cout << "拷贝构造函数调用" << endl;
		//编译器默认提供的构造函数
		this->_capacity = arr._capacity;
		this->_size = arr._size;
		//this->_myarray = arr._myarray;错误，堆区空间会二次释放
		this->_myarray = new T[this->_capacity];
		for (int i = 0; i < this->_capacity; i++)
		{
			this->_myarray[i] = arr._myarray[i];
		}
	}
	//operator=//重载=号
	MyArray& operator= (const MyArray& arr)
	{
		//cout << "运算符重载函数调用" << endl;

		//先判断原来空间是否有数据，如果有则要先销毁
		if (this->_myarray != NULL)
		{
			delete[] this->_myarray;
			this->_myarray = nullptr;
			this->_capacity = this->_size = 0;
		}
		this->_myarray = new T[arr._capacity];
		this->_capacity = arr._capacity;
		this->_size = arr._size;
		for (int i = 0; i < this->_capacity; i++)
		{
			this->_myarray[i] = arr._myarray[i];
		}
		return *this;
 	}
	//尾差法
	void PushBack(T x)
	{
		if (this->_capacity == this->_size)
		{
			return;
		}
		this->_myarray[this->_size] = x;
		this->_size++;
	}
	//尾删法
	void PopBack()
	{
		if (this->_size == 0)
		{
			return;
		}
		this->_size--;
	}
	//通过下标访问数据[]重载
	T& operator[](int index)
	{
		return  this->_myarray[index];
	}
	//返回数组容量
	int getcapacity()
	{
		return this->_capacity;
	}
	//获取数组的大小
	int getsize()
	{
		return this->_size;
	}
	//析构函数
	~MyArray()
	{
		//cout << "析构函数调用" << endl;

		if (this->_myarray != NULL)
		{
			delete[]this->_myarray;
			_myarray = nullptr;
		}
	}
};